package com.example.aidocengine.common.utils;

import com.example.aidocengine.common.exception.BusinessException;
import com.example.aidocengine.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
public class FileUtils {
    
    private static final String[] ALLOWED_EXTENSIONS = {".xlsx", ".xls", ".docx", ".doc"};
    private static final long MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

    public static boolean isValidFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }
        
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            return false;
        }
        
        // 检查文件扩展名
        String extension = getFileExtension(originalFilename);
        boolean validExtension = false;
        for (String allowedExt : ALLOWED_EXTENSIONS) {
            if (allowedExt.equalsIgnoreCase(extension)) {
                validExtension = true;
                break;
            }
        }
        
        if (!validExtension) {
            return false;
        }
        
        // 检查文件大小
        return file.getSize() <= MAX_FILE_SIZE;
    }

    public static String saveFile(MultipartFile file, String baseDir) {
        if (!isValidFile(file)) {
            throw new BusinessException(ResultCode.FILE_UPLOAD_ERROR);
        }

        try {
            // 创建基础目录
            Path basePath = Paths.get(baseDir);
            log.info("尝试创建文件保存目录：{}", basePath.toAbsolutePath());
            if (!Files.exists(basePath)) {
                Files.createDirectories(basePath);
                log.info("目录创建成功：{}", basePath.toAbsolutePath());
            } else {
                log.info("目录已存在：{}", basePath.toAbsolutePath());
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
            String newFilename = timestamp + "_" + uuid + extension;

            // 保存文件
            Path filePath = basePath.resolve(newFilename);
            file.transferTo(filePath.toFile());

            log.info("文件保存成功：{}", filePath.toString());
            return filePath.toString();
        } catch (IOException e) {
            log.error("文件保存失败：", e);
            throw new BusinessException(ResultCode.FILE_UPLOAD_ERROR);
        }
    }

    public static String getFileExtension(String filename) {
        if (StringUtils.isBlank(filename)) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf(".");
        return lastDotIndex != -1 ? filename.substring(lastDotIndex) : "";
    }

    public static String getFileBaseName(String filename) {
        if (StringUtils.isBlank(filename)) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf(".");
        return lastDotIndex != -1 ? filename.substring(0, lastDotIndex) : filename;
    }

    public static boolean deleteFile(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return false;
        }
        
        try {
            Path path = Paths.get(filePath);
            return Files.deleteIfExists(path);
        } catch (IOException e) {
            log.error("删除文件失败：{}", filePath, e);
            return false;
        }
    }

    public static boolean isExcelFile(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        return ".xlsx".equals(extension) || ".xls".equals(extension);
    }

    public static boolean isWordFile(String filename) {
        String extension = getFileExtension(filename).toLowerCase();
        return ".docx".equals(extension) || ".doc".equals(extension);
    }
}